﻿using System;
using System.ComponentModel;
using MaxStoreErp.Core.Commands;

namespace MaxStoreErp.Core.BaseClasses
{
    /// <summary>
    /// Базовый класс для ViewModel
    /// </summary>
    public class ViewModelBase : INotifyPropertyChanged
    {
        bool _isBusy;
        RelayCommand _reloadViewModelData;
        string _header = string.Empty;

        public bool IsBusy
        {
            get { return _isBusy; }
            set { OnPropertyChanged(ref _isBusy, value, "IsBusy"); }
        }

        public string Header
        {
            get { return _header; }
            set { OnPropertyChanged(ref _header, value, "Header"); }
        }

        public RelayCommand ReloadViewModelData
        {
            get { return _reloadViewModelData; }
            set { OnPropertyChanged(ref _reloadViewModelData, value, "ReloadViewModelData"); }
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected bool OnPropertyChanged<TField>(ref TField field, TField value, string propertyName)
        {
            if (Equals(field, value))
                return false;

            field = value;

            OnPropertyChanged(propertyName);
            return true;
        }

        protected bool OnPropertyChanged<TField>(ref TField field, TField value, Action onChanged, string propertyName)
        {
            if (OnPropertyChanged(ref field, value, propertyName))
            {
                var evt = onChanged;
                if (evt != null)
                {
                    evt();
                }
                return true;
            }
            return false;
        }
        #endregion
    }
}
